package pers.w.chaptertalk;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pers.w.chaptertalk.funs.BookInfo;
import pers.w.chaptertalk.funs.ChapterInfo;
import pers.w.chaptertalk.funs.Fun;
import pers.w.chaptertalk.funs.ContentThread;
import pers.w.chaptertalk.funs.IReader;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.reader.PlayerReceiver;
import pers.w.chaptertalk.reader.ReaderActivity;

public class MyService extends Service implements IReader{
    private static final String TAG = "myService";
    private static final int NOTIFICATIONS_ID = 380;
    // private static final String ACTION_PLAY = "PLAY";
    public static final String ACTION_PAUSE = "PAUSE";
    public static final String ACTION_RESUME = "RESUME";
    public static final String ACTION_STOP = "STOP";
    public static final String ACTION_SHOW_READER = "ACTION_SHOW_READ";

    public static final int REQUEST_CODE_PAUSE = 100;
    public static final int REQUEST_CODE_RESUME = 101;
    public static final int REQUEST_CODE_STOP = 102;
    public static final int REQUEST_CODE_SHOW_READER = 103;

    static final int STATUS_STOP = 0;
    static final int STATUS_PLAY = 1;
    static final int STATUS_PAUSE = 2;
    static final int STATUS_RESUME = 3;

    // Intent intentPlay = new Intent(ACTION_PLAY);// 指定操作意图--设置对应的行为ACTION
    // PendingIntent pIntentPlay = PendingIntent.getBroadcast(this.getApplicationContext(),
    //        REQUEST_CODE, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);// 取的一个PendingIntent，// 它会发送一个广播，如同Context.sendBroadcast.


    private int status = STATUS_PLAY;
    //k:long book id; v:chapter list
    private final HashMap<Long, DownloadThread> downloadMap = new HashMap<>();

    public MyService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private Notification notification;
    private RemoteViews remoteViews;
    NotificationManager manager;
    PlayerReceiver playerReceiver;

    public void createNotification(ReaderActivity reader) {
        playerReceiver = new PlayerReceiver();

        IntentFilter filter = new IntentFilter();
        // filter.addAction(ACTION_PLAY);
        filter.addAction(ACTION_STOP);
        filter.addAction(ACTION_RESUME);
        filter.addAction(ACTION_PAUSE);
        filter.addAction(ACTION_SHOW_READER);

        Context appContext = getApplicationContext();
        remoteViews = new RemoteViews(reader.getPackageName(), R.layout.notification);

        Intent intentPause = new Intent(ACTION_PAUSE);
        PendingIntent pIntentPause = PendingIntent.getBroadcast(appContext,
                REQUEST_CODE_PAUSE, intentPause, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent intentResume = new Intent(ACTION_RESUME);
        PendingIntent pIntentResume = PendingIntent.getBroadcast(appContext,
                REQUEST_CODE_RESUME, intentResume, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent intentStop = new Intent(ACTION_STOP);
        PendingIntent pIntentStop = PendingIntent.getBroadcast(appContext,
                REQUEST_CODE_STOP, intentStop, PendingIntent.FLAG_UPDATE_CURRENT);
        Intent intentShowReader = new Intent(ACTION_SHOW_READER);
        PendingIntent pIntentShowReader = PendingIntent.getBroadcast(appContext,
                REQUEST_CODE_SHOW_READER, intentShowReader, PendingIntent.FLAG_UPDATE_CURRENT);

        remoteViews.setOnClickPendingIntent(R.id.btn_spoken_resume, pIntentResume);
        remoteViews.setOnClickPendingIntent(R.id.btn_spoken_close, pIntentStop);
        remoteViews.setOnClickPendingIntent(R.id.btn_spoken_pause, pIntentPause);
        remoteViews.setOnClickPendingIntent(R.id.ll_Notification, pIntentShowReader);//单击通知栏，切回程序


        remoteViews.setViewVisibility(R.id.btn_spoken_pause, View.VISIBLE);
        remoteViews.setViewVisibility(R.id.btn_spoken_resume, View.INVISIBLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new NotificationCompat.Builder(appContext, "chaptertalk")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW)
                    .setContent(remoteViews)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();

        }else {
            Notification.Builder builder = new Notification.Builder(appContext)
                    .setContent(remoteViews);// 设置自定义的Notification内容
            builder.setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.mipmap.ic_launcher);
            notification = builder.build();
        }


        manager = (NotificationManager) reader.getSystemService(Context.NOTIFICATION_SERVICE);

        assert manager != null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("chaptertalk", "chaptertalk", NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(channel);
        }

        //  manager.notify(NOTIFICATIONS_ID, notification);
        startForeground(NOTIFICATIONS_ID, notification);
        reader.registerReceiver(playerReceiver, filter);
        status = STATUS_PLAY;
        if (Fun.isDebug()) Log.d(TAG, "createNotification: ");
    }

    @Override
    public void onDestroy() {
        stopAllDownload();
        super.onDestroy();
    }

    public void removeNotification(ReaderActivity reader) {
        if (Fun.isDebug()) Log.d(TAG, "removeNotification: ");
        if (notification != null) {
            reader.unregisterReceiver(playerReceiver);
            stopForeground(true);
            notification = null;
            playerReceiver = null;
            manager = null;
            remoteViews = null;
        }
        status = STATUS_STOP;
    }

    public boolean resume() {
        if (status == STATUS_PAUSE) {
            remoteViews.setViewVisibility(R.id.btn_spoken_pause, View.VISIBLE);
            remoteViews.setViewVisibility(R.id.btn_spoken_resume, View.GONE);
            status = STATUS_RESUME;
            manager.notify(NOTIFICATIONS_ID, notification);
            return true;
        }
        return false;
    }

    public boolean pause() {
        if (status == STATUS_PLAY || status == STATUS_RESUME) {
            remoteViews.setViewVisibility(R.id.btn_spoken_pause, View.GONE);
            remoteViews.setViewVisibility(R.id.btn_spoken_resume, View.VISIBLE);
            status = STATUS_PAUSE;
            manager.notify(NOTIFICATIONS_ID, notification);
            return true;
        }
        return false;
    }

    MyIBinder binder = new MyIBinder();

    public class MyIBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    public final static int DOWNLOAD_HAS = -1;
    public final static int DOWNLOAD_TOO_MUCH = 0;
    public final static int DOWNLOAD_OK = 1;
    public final static int DOWNLOAD_NODATA =2;
   // public static int DOWNLOAD_NO_NET = 2;


    public int addDownload(BookInfo book, List<Map<String, String>> chapters) {
        if (downloadMap.size() >= 3) return DOWNLOAD_TOO_MUCH;
        if (null==chapters){
            Tab_Book tab_book= new Tab_Book(this);
            chapters =tab_book.getTab_chapter().get_chapters(book.getID());
            tab_book.close();
        }
        if (chapters.size()==0) return DOWNLOAD_NODATA;

        long bookID =book.getID();
        if (downloadMap.get(bookID) == null) {
            DownloadThread cache = new DownloadThread(book, downloadMap, chapters);
            cache.start();
            synchronized (downloadMap) {
                downloadMap.put(bookID, cache);
            }
            return DOWNLOAD_OK;
        } else return DOWNLOAD_HAS;
    }

    public void stopDownload(Long bookID) {
        DownloadThread cache = downloadMap.get(bookID);
        if (cache != null) {
            cache.setStop();
            downloadMap.remove(bookID);
        }
    }

    public void stopAllDownload() {
        for (DownloadThread cache : downloadMap.values()) {
            cache.setStop();
        }
        downloadMap.clear();
    }

    private Handler handler = new Handler((msg)->{
        if (HANDLER_GET_CONTENT == msg.what){
            BookInfo book = (BookInfo) msg.obj;
            synchronized (downloadMap) {
                downloadMap.remove(book.getID());
            }
            Toast.makeText(MyService.this.getApplicationContext(),
                    book.getFieldValue(R.string.info_name) + "：结束缓存", Toast.LENGTH_SHORT).show();
            return true;
        }
          return false;
    });
    private  class DownloadThread extends ContentThread {

        private BookInfo book;
        final Map<Long, DownloadThread> downloadMap;

        DownloadThread(BookInfo book, Map<Long, DownloadThread> downloadMap, List<Map<String, String>> chapters) {
            super(null, 0, book.getBookDir(), chapters);
            this.book = book;
            this.downloadMap = downloadMap;
        }

        @Override
        public void run() {
            super.run();
            handler.sendMessage(handler.obtainMessage(HANDLER_GET_CONTENT,0,0,book));
        }
    }
}
